package com.ruoyi.home.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.art.domain.ArtGood;
import com.ruoyi.art.service.IArtGoodService;
import com.ruoyi.campus.domain.vo.CampusVO;
import com.ruoyi.campus.service.ICampusService;
import com.ruoyi.home.domain.SuBannerAds;
import com.ruoyi.home.domain.SuQuickEntries;
import com.ruoyi.home.service.ISuBannerAdsService;
import com.ruoyi.home.service.ISuQuickEntriesService;
import com.ruoyi.home.service.MiniprogramGeneratorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 小程序代码生成服务实现类
 * 
 * @author ruoyi
 * @date 2025-01-21
 */
@Service
public class MiniprogramGeneratorServiceImpl implements MiniprogramGeneratorService 
{
    @Autowired
    private ISuBannerAdsService bannerAdsService;
    
    @Autowired
    private IArtGoodService artGoodService;
    
    @Autowired
    private ISuQuickEntriesService quickEntriesService;
    
    @Autowired
    private ICampusService campusService;

    @Override
    public Map<String, String> generateMiniProgramCode(Map<String, Object> pageData) 
    {
        Map<String, String> codeFiles = new HashMap<>();
        
        try {
            // 生成WXML代码
            String wxmlCode = generateWXML(pageData);
            codeFiles.put("index.wxml", wxmlCode);
            
            // 生成WXSS代码
            String wxssCode = generateWXSS(pageData);
            codeFiles.put("index.wxss", wxssCode);
            
            // 生成JS代码
            String jsCode = generateJS(pageData);
            codeFiles.put("index.js", jsCode);
            
            // 生成JSON配置
            String jsonCode = generateJSON(pageData);
            codeFiles.put("index.json", jsonCode);
            
        } catch (Exception e) {
            throw new RuntimeException("生成小程序代码失败: " + e.getMessage(), e);
        }
        
        return codeFiles;
    }

    @Override
    public void downloadMiniProgramCode(Map<String, Object> pageData, HttpServletResponse response) throws IOException 
    {
        // 生成代码文件
        Map<String, String> codeFiles = generateMiniProgramCode(pageData);
        
        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=miniprogram-page.zip");
        
        // 创建ZIP输出流
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            for (Map.Entry<String, String> entry : codeFiles.entrySet()) {
                ZipEntry zipEntry = new ZipEntry(entry.getKey());
                zos.putNextEntry(zipEntry);
                zos.write(entry.getValue().getBytes(StandardCharsets.UTF_8));
                zos.closeEntry();
            }
        }
    }

    @Override
    public Long saveDraft(Map<String, Object> draftData) 
    {
        // 这里可以保存到数据库，暂时返回一个模拟的ID
        // 实际项目中需要创建草稿表并保存
        return System.currentTimeMillis();
    }

    @Override
    public Map<String, Object> getDraftList(Integer pageNum, Integer pageSize) 
    {
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("rows", new ArrayList<>());
        // 实际项目中需要从数据库查询草稿列表
        return result;
    }

    @Override
    public Map<String, Object> getDraft(Long draftId) 
    {
        Map<String, Object> draft = new HashMap<>();
        draft.put("id", draftId);
        draft.put("components", new ArrayList<>());
        draft.put("config", new HashMap<>());
        // 实际项目中需要从数据库查询具体草稿内容
        return draft;
    }

    @Override
    public void deleteDraft(Long draftId) 
    {
        // 实际项目中需要从数据库删除草稿
    }

    @Override
    public Object getComponentData(String type, Long campusId) 
    {
        switch (type) {
            case "banner":
                SuBannerAds bannerQuery = new SuBannerAds();
                bannerQuery.setStatus(1); // 只获取已上架的
                return bannerAdsService.selectSuBannerAdsList(bannerQuery);
                
            case "goods":
                ArtGood goodQuery = new ArtGood();
                if (campusId != null) {
                    goodQuery.setCampusId(campusId);
                }
                goodQuery.setGoodStatus(0L); // 已上架
                return artGoodService.selectArtGoodList(goodQuery);
                
            case "quick":
                SuQuickEntries quickQuery = new SuQuickEntries();
                quickQuery.setStatus(1); // 已上架
                return quickEntriesService.selectSuQuickEntriesList(quickQuery);
                
            case "campus":
                try {
                    CampusVO campusQuery = new CampusVO();
                    campusQuery.setCampusStatus(1); // 正常状态
                    return campusService.selectCampusList(campusQuery);
                } catch (Exception e) {
                    return new ArrayList<>();
                }
                
            default:
                return new ArrayList<>();
        }
    }

    /**
     * 生成WXML代码
     */
    private String generateWXML(Map<String, Object> pageData) 
    {
        StringBuilder wxml = new StringBuilder();
        wxml.append("<!--index.wxml-->\n");
        wxml.append("<view class=\"container\">\n");
        wxml.append("  <!-- 状态栏 -->\n");
        wxml.append("  <view class=\"status-bar\"></view>\n\n");
        
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> components = (List<Map<String, Object>>) pageData.get("components");
        
        if (components != null) {
            for (Map<String, Object> component : components) {
                wxml.append(generateComponentWXML(component));
            }
        }
        
        wxml.append("</view>");
        return wxml.toString();
    }

    /**
     * 生成组件WXML
     */
    private String generateComponentWXML(Map<String, Object> component) 
    {
        String type = (String) component.get("type");
        @SuppressWarnings("unchecked")
        Map<String, Object> data = (Map<String, Object>) component.get("data");
        
        StringBuilder wxml = new StringBuilder();
        
        switch (type) {
            case "campus":
                wxml.append("  <!-- 校区名称 -->\n");
                wxml.append("  <view class=\"campus-header\">\n");
                wxml.append("    <text class=\"campus-name\">{{campusName}}</text>\n");
                wxml.append("  </view>\n\n");
                break;
                
            case "search":
                String placeholder = data != null ? (String) data.get("placeholder") : "搜索课程、商品...";
                wxml.append("  <!-- 搜索框 -->\n");
                wxml.append("  <view class=\"search-container\">\n");
                wxml.append("    <view class=\"search-box\">\n");
                wxml.append("      <icon class=\"search-icon\" type=\"search\" size=\"16\"></icon>\n");
                wxml.append("      <input class=\"search-input\" placeholder=\"").append(placeholder).append("\" />\n");
                wxml.append("    </view>\n");
                wxml.append("  </view>\n\n");
                break;
                
            case "banner":
                Boolean autoPlay = data != null ? (Boolean) data.get("autoPlay") : true;
                Integer interval = data != null ? (Integer) data.get("interval") : 3000;
                wxml.append("  <!-- 轮播图 -->\n");
                wxml.append("  <view class=\"banner-container\">\n");
                wxml.append("    <swiper class=\"banner-swiper\" indicator-dots=\"{{true}}\" autoplay=\"{{").append(autoPlay).append("}}\" interval=\"{{").append(interval).append("}}\">\n");
                wxml.append("      <swiper-item wx:for=\"{{bannerList}}\" wx:key=\"id\">\n");
                wxml.append("        <image class=\"banner-image\" src=\"{{item.image}}\" mode=\"aspectFill\" bindtap=\"onBannerTap\" data-link=\"{{item.link}}\"></image>\n");
                wxml.append("      </swiper-item>\n");
                wxml.append("    </swiper>\n");
                wxml.append("  </view>\n\n");
                break;
                
            case "goods":
                wxml.append("  <!-- 商品展示 -->\n");
                wxml.append("  <view class=\"goods-container\">\n");
                wxml.append("    <view class=\"goods-grid\">\n");
                wxml.append("      <view class=\"goods-item\" wx:for=\"{{goodsList}}\" wx:key=\"id\" bindtap=\"onGoodsTap\" data-id=\"{{item.id}}\">\n");
                wxml.append("        <image class=\"goods-image\" src=\"{{item.goodPicture}}\" mode=\"aspectFill\"></image>\n");
                wxml.append("        <view class=\"goods-info\">\n");
                wxml.append("          <text class=\"goods-name\">{{item.goodName}}</text>\n");
                wxml.append("          <text class=\"goods-price\">¥{{item.goodMemberPrice}}</text>\n");
                wxml.append("        </view>\n");
                wxml.append("      </view>\n");
                wxml.append("    </view>\n");
                wxml.append("  </view>\n\n");
                break;
                
            case "quick":
                wxml.append("  <!-- 快捷入口 -->\n");
                wxml.append("  <view class=\"quick-container\">\n");
                wxml.append("    <view class=\"quick-grid\">\n");
                wxml.append("      <view class=\"quick-item\" wx:for=\"{{quickEntries}}\" wx:key=\"id\" bindtap=\"onQuickTap\" data-link=\"{{item.link}}\">\n");
                wxml.append("        <text class=\"quick-name\">{{item.name}}</text>\n");
                wxml.append("      </view>\n");
                wxml.append("    </view>\n");
                wxml.append("  </view>\n\n");
                break;
        }
        
        return wxml.toString();
    }

    /**
     * 生成WXSS代码
     */
    private String generateWXSS(Map<String, Object> pageData) 
    {
        StringBuilder wxss = new StringBuilder();
        
        @SuppressWarnings("unchecked")
        Map<String, Object> config = (Map<String, Object>) pageData.get("config");
        String backgroundColor = config != null ? (String) config.get("backgroundColor") : "#f5f5f5";
        
        wxss.append("/* index.wxss */\n");
        wxss.append(".container {\n");
        wxss.append("  background-color: ").append(backgroundColor).append(";\n");
        wxss.append("  min-height: 100vh;\n");
        wxss.append("}\n\n");
        
        wxss.append(".status-bar {\n");
        wxss.append("  height: var(--status-bar-height);\n");
        wxss.append("}\n\n");
        
        // 添加各组件的基础样式
        wxss.append(getBasicComponentStyles());
        
        return wxss.toString();
    }

    /**
     * 生成JS代码
     */
    private String generateJS(Map<String, Object> pageData) 
    {
        StringBuilder js = new StringBuilder();
        
        js.append("// index.js\n");
        js.append("Page({\n");
        js.append("  data: {\n");
        js.append("    campusName: '默认校区',\n");
        js.append("    bannerList: [],\n");
        js.append("    goodsList: [],\n");
        js.append("    quickEntries: []\n");
        js.append("  },\n\n");
        
        js.append("  onLoad(options) {\n");
        js.append("    this.loadPageData()\n");
        js.append("  },\n\n");
        
        js.append("  loadPageData() {\n");
        js.append("    this.loadBannerData()\n");
        js.append("    this.loadGoodsData()\n");
        js.append("    this.loadQuickEntries()\n");
        js.append("  },\n\n");
        
        js.append("  loadBannerData() {\n");
        js.append("    wx.request({\n");
        js.append("      url: 'https://your-api-domain.com/api/banners',\n");
        js.append("      success: (res) => {\n");
        js.append("        this.setData({ bannerList: res.data })\n");
        js.append("      }\n");
        js.append("    })\n");
        js.append("  },\n\n");
        
        js.append("  onBannerTap(e) {\n");
        js.append("    const link = e.currentTarget.dataset.link\n");
        js.append("    if (link) {\n");
        js.append("      wx.navigateTo({ url: link })\n");
        js.append("    }\n");
        js.append("  },\n\n");
        
        js.append("  onGoodsTap(e) {\n");
        js.append("    const goodsId = e.currentTarget.dataset.id\n");
        js.append("    wx.navigateTo({ url: '/pages/goods/detail?id=' + goodsId })\n");
        js.append("  },\n\n");
        
        js.append("  onQuickTap(e) {\n");
        js.append("    const link = e.currentTarget.dataset.link\n");
        js.append("    if (link) {\n");
        js.append("      wx.navigateTo({ url: link })\n");
        js.append("    }\n");
        js.append("  }\n");
        
        js.append("})");
        
        return js.toString();
    }

    /**
     * 生成JSON配置
     */
    private String generateJSON(Map<String, Object> pageData) 
    {
        Map<String, Object> config = new HashMap<>();
        config.put("usingComponents", new HashMap<>());
        
        @SuppressWarnings("unchecked")
        Map<String, Object> pageConfig = (Map<String, Object>) pageData.get("config");
        
        String title = pageConfig != null ? (String) pageConfig.get("title") : "艺术教育";
        String backgroundColor = pageConfig != null ? (String) pageConfig.get("backgroundColor") : "#f5f5f5";
        
        config.put("navigationBarTitleText", title);
        config.put("navigationBarBackgroundColor", "#ffffff");
        config.put("navigationBarTextStyle", "black");
        config.put("backgroundColor", backgroundColor);
        config.put("enablePullDownRefresh", true);
        config.put("onReachBottomDistance", 50);
        
        return JSON.toJSONString(config);
    }

    /**
     * 获取基础组件样式
     */
    private String getBasicComponentStyles() 
    {
        return "/* 校区名称样式 */\n" +
               ".campus-header {\n" +
               "  padding: 10px 20px;\n" +
               "  background-color: transparent;\n" +
               "}\n\n" +
               ".campus-name {\n" +
               "  font-size: 18px;\n" +
               "  color: #333;\n" +
               "  font-weight: bold;\n" +
               "}\n\n" +
               "/* 搜索框样式 */\n" +
               ".search-container {\n" +
               "  padding: 15px 20px;\n" +
               "}\n\n" +
               ".search-box {\n" +
               "  display: flex;\n" +
               "  align-items: center;\n" +
               "  background-color: #f0f0f0;\n" +
               "  border-radius: 20px;\n" +
               "  padding: 10px 15px;\n" +
               "}\n\n" +
               ".search-icon {\n" +
               "  margin-right: 10px;\n" +
               "  color: #999;\n" +
               "}\n\n" +
               ".search-input {\n" +
               "  flex: 1;\n" +
               "  font-size: 14px;\n" +
               "}\n\n" +
               "/* 轮播图样式 */\n" +
               ".banner-container {\n" +
               "  margin: 15px 20px;\n" +
               "}\n\n" +
               ".banner-swiper {\n" +
               "  height: 160px;\n" +
               "  border-radius: 8px;\n" +
               "  overflow: hidden;\n" +
               "}\n\n" +
               ".banner-image {\n" +
               "  width: 100%;\n" +
               "  height: 100%;\n" +
               "}\n\n" +
               "/* 商品展示样式 */\n" +
               ".goods-container {\n" +
               "  padding: 15px 20px;\n" +
               "  background-color: #fff;\n" +
               "  border-radius: 8px;\n" +
               "  margin: 15px 20px;\n" +
               "}\n\n" +
               ".goods-grid {\n" +
               "  display: grid;\n" +
               "  grid-template-columns: repeat(2, 1fr);\n" +
               "  gap: 15px;\n" +
               "}\n\n" +
               ".goods-item {\n" +
               "  background: #fff;\n" +
               "  border-radius: 8px;\n" +
               "  overflow: hidden;\n" +
               "  box-shadow: 0 2px 8px rgba(0,0,0,0.1);\n" +
               "}\n\n" +
               ".goods-image {\n" +
               "  width: 100%;\n" +
               "  height: 120px;\n" +
               "}\n\n" +
               ".goods-info {\n" +
               "  padding: 10px;\n" +
               "}\n\n" +
               ".goods-name {\n" +
               "  display: block;\n" +
               "  font-size: 14px;\n" +
               "  color: #333;\n" +
               "  margin-bottom: 8px;\n" +
               "}\n\n" +
               ".goods-price {\n" +
               "  font-size: 16px;\n" +
               "  color: #ff4757;\n" +
               "  font-weight: bold;\n" +
               "}\n\n" +
               "/* 快捷入口样式 */\n" +
               ".quick-container {\n" +
               "  padding: 15px 20px;\n" +
               "  background-color: #fff;\n" +
               "  margin: 15px 20px;\n" +
               "  border-radius: 8px;\n" +
               "}\n\n" +
               ".quick-grid {\n" +
               "  display: grid;\n" +
               "  grid-template-columns: repeat(4, 1fr);\n" +
               "  gap: 15px;\n" +
               "}\n\n" +
               ".quick-item {\n" +
               "  text-align: center;\n" +
               "  padding: 10px;\n" +
               "}\n\n" +
               ".quick-name {\n" +
               "  font-size: 12px;\n" +
               "  color: #666;\n" +
               "}\n\n";
    }
} 